package com.xuhuan.demo.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * @Author huan.xu
 * @Date 2023/7/8 14:51
 * @Description 文件md5工具类
 */
public class FileMd5Util {

    private FileMd5Util() {
    }

    /**
     * 获取文件md5值
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String md5HashCode(String filePath) throws Exception {
        return md5HashCode(new File(filePath));
    }

    /**
     * 获取文件md5值
     *
     * @param file 文件
     * @return
     * @throws Exception
     */
    public static String md5HashCode(File file) throws Exception {
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        InputStream fis = new FileInputStream(file);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = fis.read(buffer, 0, 1024)) != -1) {
            md.update(buffer, 0, length);
        }
        fis.close();

        //转换并返回包含16个元素字节数组,返回数值范围为-128到127
        byte[] md5Bytes = md.digest();
        BigInteger bigInt = new BigInteger(1, md5Bytes);
        String md5HashCode = bigInt.toString(16);
        return md5HashCode;
    }
}
